package com.xjt.wx_admin.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjt.wx_admin.entity.User;
import com.xjt.wx_admin.entity.dto.LoginParam;
import com.xjt.wx_admin.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class LoginUserServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.error("弃用...");
        return null;
    }


    public UserDetails loadUserByUsername(LoginParam loginParam) throws UsernameNotFoundException {
        if (loginParam.getLoginType().equals(2)){
            User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                    .eq(User::getUserName,loginParam.getUserName())
            );
            if (user == null){
                user =  new User(loginParam.getUserName(), loginParam.getPassword());
                userMapper.insert(user);
                return new LoginUser(user);
            }else {
                if (encoder.matches(loginParam.getPassword(), user.getPassword())) {
                    return new LoginUser(user);
                }else {
                    throw new UsernameNotFoundException("密码异常");
                }
            }
        }else {
            String ip = loginParam.getIp();
            ip = ip.replace(".","");
            User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                    .eq(User::getUserName,ip)
            );
            if (user==null){
                user = new User(ip);
                userMapper.insert(user);
            }
            return new LoginUser(user);
        }
    }
}
